<!--
 * @Description: App端分享注册页面
 * @Author: Kerwin
 * @Date: 2024-08-28 17:36:15
 * @LastEditTime: 2025-11-11 17:04:47
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="container">
    <!-- <u-navbar back-text="" title="注册" v-if="!isWeChatOfficial" :title-bold="false" color="#000"></u-navbar> -->
    <view style="position: relative; z-index: 2; background-color: #fff">
      <view class="logoBox">
        <view class="left">
          <view class="logoBox">
            <image
              class="logo"
              src="https://www.blacksilverscore.com/download/img/hello.png"
            ></image>
            <view class="textColor" @click="goHome">返回用户登录</view>
          </view>
          <view class="titleBox"
            ><text class="title">欢迎注册黑银App</text
            ><text class="textColor" @click="toDownload"
              >下载APP享优惠 !</text
            ></view
          >
        </view>
      </view>
      <u-form :model="form" ref="formRef">
        <u-form-item label="手机号" prop="phone" label-width="120">
          <u-input
            v-model="form.phone"
            type="number"
            :maxlength="11"
            placeholder="请输入手机号"
          />
        </u-form-item>
        <u-form-item label="验证码" prop="code" label-width="120">
          <u-input
            v-model="form.code"
            type="number"
            :maxlength="6"
            placeholder="请输入验证码"
          />
          <u-verification-code
            :seconds="seconds"
            ref="uCode"
            @change="codeChange"
          ></u-verification-code>
          <u-button @tap="getCode" size="mini" type="success" ripple>{{
            tips
          }}</u-button>
        </u-form-item>
        <u-form-item label="密码" prop="password" label-width="120">
          <u-input
            v-model="form.password"
            :maxlength="18"
            placeholder="请设置密码"
          />
        </u-form-item>
        <u-form-item label="邀请码" prop="inviteCode" label-width="120">
          <u-input
            v-model="form.inviteCode"
            :maxlength="6"
            :disabled="disabled"
            placeholder="请输入邀请码"
          />
        </u-form-item>
      </u-form>
      <u-button @click="submit" class="btn" ripple shape="circle"
        >立即注册</u-button
      >
      <view class="user-agreement">
        点击注册意味着您同意
        <a
          href="https://www.blacksilverscore.com/download/user_agreement_license.html"
          >《用户协议》</a
        >
      </view>
    </view>
    <!-- <hyDownloadTips v-if="form.inviteCode" :top="'0px'" /> -->
    <image
      src="https://www.blacksilverscore.com/download/img/regiest_bg.png"
      mode="widthFix"
      class="footerbg"
    />

    <!-- 授权弹窗 -->

    <!-- 确认换绑弹窗 -->
    <c_innovateBox
      ref="innovateRef"
      :invite-code="form.inviteCode"
      :innovateType="innovateType"
      :shopId="shopId"
    />
  </view>
</template>
<script setup lang="ts">
import { reactive, ref, computed, nextTick } from 'vue'
import { onLoad, onReady } from '@dcloudio/uni-app'
import { Md5 } from 'ts-md5'
import { useUserStore } from '@/store'
import { baseApi, userApi, enumAll } from '@/api'
import { getQueryVariable, isWeChat, route, getCookie } from '@/utils/common'
import { hy_logo } from '@/common/config'
import c_innovateBox from './c_innovateBox.vue'
import { useConfigStore } from '@/store'
import { innovate_type, innovate_shopId } from '@/api/enum'
import hyDownloadTips from '@/components/hy-download-tips/index.vue'
import { log } from 'console'
const userStore = useUserStore()
const isWeChatOfficial = ref(true)
const configStore = useConfigStore()
// #ifdef MP-WEIXIN
isWeChatOfficial.value = false
// #endif
const form = reactive({
  password: '',
  code: '',
  phone: '',
  inviteCode: ''
})
const uCode = ref()
const tips = ref('获取验证码')
const seconds = ref(60)
function codeChange(text: string) {
  tips.value = text
}
async function getCode() {
  if (!form.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none'
    })
    return
  }
  if (uCode.value.canGetCode) {
    if (uni.getStorageSync('accessToken')) {
      uni.removeStorageSync('accessToken')
    }

    try {
      const { data } = await baseApi.smsSend({
        type: enumAll.sms_enum_type.RegisterCode,
        phone: form.phone
      })
      uCode.value.start()
    } catch {}
  }
}

//返回用户登录
function goHome() {
  route({
    url: '/pages/login/index'
  })
}

//下载app
function toDownload() {
  window.open('https://www.blacksilverscore.com/download/index.html')
}

function submit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      try {
        uni.showLoading({
          title: '提交中',
          mask: true
        })
        const params = {
          loginType: userApi.LOGIN_TYPE_ENUM.PWD,
          phone: form.phone,
          code: form.code,
          password: Md5.hashStr(form.password),
          openId: userStore.openid,
          unionId: userStore.unionid,
          mode: shopId.value == 3381 ? 1 : shopId.value == 3382 ? 4 : 0
        }
        const shopCode = uni.getStorageSync('shopCode')
        const shareCode = uni.getStorageSync('shareCode')
        const deviceSn = uni.getStorageSync('deviceSn')
        const shopOwnerShareCode = uni.getStorageSync('shopOwnerShareCode')
        if (shareCode) {
          // @ts-ignore
          params.inviteCode = shareCode
        } else if (shopOwnerShareCode) {
          // @ts-ignore
          params.inviteCode = shopOwnerShareCode
        } else if (shopCode) {
          // @ts-ignore
          params.shopCode = shopCode
        }
        if (deviceSn) {
          // @ts-ignore
          params.inviteDeviceCode = deviceSn
        }
        try {
          const { data } = await userApi.register(params)
          userStore.syncSetToken(data.accessToken)
          await updateUserInfo()
          await userStore.getUserInfo()
          if (innovateType.value) {
            bindRelation()
            // innovateRef.value.open(userStore.userInfo.id)
          } else {
            // #ifdef H5
            route({
              url: '/pages/register/success'
            })
            // uni.redirectTo({ url: '/pages/launch/index' })
            // #endif
          }
        } catch (err: any) {
          if (err.data.id) {
            if (innovateType.value) {
              innovateRef.value.open(err.data.id)
            }
          }
        }
        uni.hideLoading()
      } catch {}
    } else {
      console.log('验证失败')
    }
  })
}

async function updateUserInfo() {
  uni.showLoading({
    title: '用户信息更新中'
  })
  await userApi
    .userInfoUpdate({
      nickname:
        userStore.wxUserInfoGetter?.nickname ||
        form.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') ||
        '',
      avatar: userStore.wxUserInfoGetter?.headimgurl || '',
      inviteCode:form.inviteCode

    })
    .finally(() => {
      uni.hideLoading()
    })
}

const formRef = ref()
const rules = {
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    {
      pattern: /^(?:\d+|[a-zA-Z]+|[!@#$%^&*]+){6,18}$/,
      message: '密码由6-18位数字、英文或特殊字符组成!',
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码长度为6位', trigger: 'blur' }
  ],
  inviteCode: [
    { required: true, message: '请输入邀请码', trigger: 'blur' },
    { min: 6, max: 6, message: '邀请码长度为6位', trigger: 'blur' }
  ]
}

const showAuth = ref(false)
async function handleWxWebLogin() {
  const { code } = await userStore.wxAuth()
  console.log('注册登录页面的code', code)
}

const withShareCode = ref(false)
const disabled = computed(() => {
  return withShareCode.value
})
const innovateRef = ref()
const innovateType = ref()
const shopId = ref()
//初始化数据
onLoad(async (option) => {
  console.log(
    'sharecode==>',
    option?.shareCode,
    uni.getStorageSync('shareCode')
  )
  console.log(
    'innovateType==>',
    option?.innovateType,
    uni.getStorageSync('innovateType')
  )
  console.log('shopId==>', option?.shopId, uni.getStorageSync('shopId'))
  console.log(
    '注册的token ==》',
    uni.getStorageSync('accessToken'),
    'cookie==>',
    getCookie('HYToken')
  )

  withShareCode.value = !!option?.shareCode
  if (option?.innovateType) {
    innovateType.value = option?.innovateType
    shopId.value = option?.shopId
  }

  // #ifdef H5
  isWeChatOfficial.value = isWeChat()
  // #endif
  const shopCode = uni.getStorageSync('shopCode')
  const shareCode = option?.shareCode || uni.getStorageSync('shareCode')
  const shopOwnerShareCode = uni.getStorageSync('shopOwnerShareCode')
  if (shareCode) {
    form.inviteCode = shareCode
  } else if (shopOwnerShareCode) {
    form.inviteCode = shopOwnerShareCode
  } else if (shopCode) {
    form.shopCode = shopCode
  }
  console.log('form==>', form)
  if (isWeChatOfficial.value) {
    const code = getQueryVariable('code')
    showAuth.value = !code
    if (code) {
      await userStore.wxWebLogin(code)
      const login_success = await userStore.loginByOpenId()
      if (login_success) {
        //微信授权成功，是老用户，有没有shopid
        if (innovateType.value) {
          bindRelation()
          // innovateRef.value.open(userStore.userInfo.id)
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      }
    }
  }
})
onReady(() => {
  formRef.value.setRules(rules)
})

//绑定关系
async function bindRelation() {
  if (innovateType.value == 0 && !shopId.value) {
    console.error('shopId 未正确设置')
    uni.showToast({
      title: '店铺id 未正确设置',
      icon: 'none',
      duration: 3000
    })
    return
  }
if(!form.inviteCode){
  console.log('请输入邀请码');
  uni.showToast({
    title: '请输入邀请码',
    icon: 'none',
    duration: 3000
  })
  return
}


  console.log('要墙面',form.inviteCode);
  
return
  try {
    const res = await userApi.innovateBind({
      userId: userStore.userInfo.id,
      shareCode: form.inviteCode,
      innovateType: innovateType.value == 0 ? 3 : innovateType.value,
      shopId:
        innovateType.value == 0 && shopId.value
          ? shopId.value
          : innovate_shopId[innovateType.value as keyof typeof innovate_shopId]
      // shopId: innovate_shopId[innovateType.value  as keyof typeof innovate_shopId]
    })

    uni.removeStorageSync('innovateType')

    if (res.code == 200) {
      uni.showToast({
        title: '绑定成功',
        icon: 'none',
        duration: 4000,
        success: () => {
          if (configStore.isWeChatBrowser) {
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }, 1000)
          }
        }
      })
    }
  } catch (error: any) {
    // 检查错误码是否为 500
    if (error?.code === 500) {
      // 执行页面跳转到首页
      uni.switchTab({
        url: '/pages/index/index'
      })
    } else {
      // 其他错误处理
      uni.showToast({
        title: '绑定失败，请联系客服',
        icon: 'none',
        duration: 3000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  max-width: 750rpx;
  margin: 0 auto;
}

.container {
  background: #fff;
  overflow: hidden;
  min-height: 100vh;
  padding: 30rpx;
  position: relative;

  .logoBox {
    display: flex;
    justify-content: space-between;
    text-align: left;
    margin-bottom: 50rpx;
    .left {
      width: 100%;
      .logoBox {
        display: flex;
        justify-content: space-between;

        .logo {
          width: 168rpx;
          height: 44rpx;
          // margin: 0 auto;
          // margin-top: 30rpx;
          // border-radius: 10rpx;
        }
      }

      .titleBox {
        margin-top: 40rpx;

        // display: flex;
        // align-items: center;
        // justify-content: space-between;
        .title {
          font-size: 40rpx;
          font-weight: 500;
          color: #268bcc;
          margin-top: 40rpx;
          margin-right: 40rpx;
        }
      }
    }
  }

  .btn {
    color: #ffffff;
    text-align: center;
    justify-content: center;
    width: 632rpx;
    height: 88rpx;
    background: linear-gradient(0deg, #54a4d8 0%, #268bcc 100%);
    margin: 0 auto;
    margin-top: 60rpx !important;
    font-size: 36rpx;
  }

  .user-agreement {
    font-size: 24rpx;
    font-weight: 400;
    color: #666666;
    margin-top: 40rpx;
    text-align: center;

    a {
      color: rgba(42, 142, 205, 1) !important;
      border: none;
      text-decoration: none;
    }
  }

  .footerbg {
    position: absolute;
    display: block;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 1;
  }
}

.authBox {
  padding: 30rpx;

  .tit {
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .label {
      margin-left: 10rpx;
    }
  }

  .desc {
    &-tit {
      font-size: 28rpx;
      color: #333333;
      margin-top: 30rpx;
      font-weight: bold;
    }

    &-txt {
      font-size: 24rpx;
      color: #666666;
      margin-top: 10rpx;
    }
  }

  .content {
    padding: 30rpx 0;

    .hy-icon-wechat {
      color: #fff;
      margin-right: 15rpx;
      font-size: 36rpx;
    }
  }
}

.textColor {
  color: #268bcc;
}
</style>
